home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3275 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Please help ?!
  5. Date: Sat, 27 Jan 1996 13:12:53 GMT
  6. Organization: Netcom
  7. Message-ID: <310a2389.49571776@nntp.ix.netcom.com>
  8. References: <4dm889$3hs@neptunus.pi.net> <4drnv1$cr@news.iag.net> <4drq5i$cr@news.iag.net> <4e6hse$dvl@ns.RezoNet.NET>
  9. NNTP-Posting-Host: ix-dc9-18.ix.netcom.com
  10. X-NETCOM-Date: Sat Jan 27  5:12:58 AM PST 1996
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. ray@ultimate-tech.com (Ray Dunn) wrote:
  14.  
  15. > In referenced article, John R Buchan says...
  16. > >>   cpy = (char *) malloc(MAXLEN);
  17. > >
  18. > >The cast is unnecessary and can hide errors.  You should remove it.
  19. > This is the second time I've seen this advice in the last five minutes 
  20. > in the newsgroup.
  21. > Certainly the cast is unnecessary, and certainly *some* unnecessary 
  22. > casts can hide errors, but casting the result of malloc can *never* 
  23. > hide an error, because it's telling the compiler to do something it 
  24. > would do anyway.
  25. > On the other hand, if by any chance "cpy" is not a "char *", but you 
  26. > thought it was when you wrote the statement, then including the cast 
  27. > will *catch* an error.
  28. > I'd go as far as to say that if the argument of malloc, calloc, 
  29. > etc. contains a sizeof operator such that a number of elements of that 
  30. > type are being allocated, then adding a cast to a pointer of the same 
  31. > type to the malloc return is the *safest* thing you can do:
  32. >   fred = malloc(n * sizeof(int));
  33. > Oops - fred isn't an "int *" it's a "long *", but the compiler wont 
  34. > issue any warnings, but in:
  35. >   fred = (int *)malloc(n * sizeof(int));
  36. > the compiler will issue an error.
  37.  
  38. Why will the compiler issue an error in that case?  It's completely
  39. legal code.
  40.  
  41. The error that can be hidden by a cast is omitting the declaration of
  42. malloc() and not including stdlib.h.  Without the cast a diagnostic is
  43. required since an int cannot be automatically converted to a pointer.
  44. With the cast the compiler will convert the int it thinks is returned
  45. by malloc() to a pointer and few compilers will give any indication of
  46. the error (read: none that I'm aware of).
  47.  
  48.  
  49. Michael M Rubenstein
  50.